"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: generator.py
@DateTime: 2025/07/07
@Docs: 权限自动生成器
"""

from app.services.permission.registry import permission_registry


class PermissionGenerator:
    """权限自动生成器

    根据模型名称，自动生成标准的CRUD权限并注册。
    """

    def __init__(self, model_name: str, module_name: str = "system", actions: list[str] | None = None):
        """
        Args:
            model_name (str): 模型名称，例如 'User' 或 'Role'
            module_name (str): 权限所属模块，默认为 'system'
            actions (list[str] | None): 需要生成的权限动作列表。
                                       如果为 None，则使用默认的 ['list', 'create', 'view', 'update', 'delete']
        """
        self.model_name = model_name.lower()
        self.module_name = module_name.lower()
        self.actions = actions or ["list", "create", "view", "update", "delete"]

    def generate_and_register(self) -> None:
        """为模型生成并注册标准的CRUD权限"""
        action_map = {
            "list": "列表",
            "create": "创建",
            "view": "详情",
            "update": "更新",
            "delete": "删除",
        }

        for action in self.actions:
            code = f"{self.module_name}:{self.model_name}:{action}"
            # e.g. "用户列表" or "角色创建"
            name = f"{self.model_name.capitalize()} {action_map.get(action, action.capitalize())}"
            description = f"允许 {action} {self.model_name}."

            permission_registry.register(
                code=code,
                name=name,
                description=description,
                module=self.module_name,
                resource=self.model_name,
                action=action,
                type="model",
            )
